<?php

namespace app\admin\controller\health;

use app\common\controller\Backend;
use app\health\model\HealthCoupon;
use app\health\model\HealthGoods;
use Exception;
use think\Db;

/**
 * 优惠券管理
 * @icon fa fa-circle-o
 */
class Coupon extends Backend
{

    /**
     * HealthCoupon模型对象
     * @var HealthCoupon
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new HealthCoupon();
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $searchWhere = $this->request->request('searchWhere');
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);
            return $this->success('优惠券', null, $result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加优惠券
     * @Author 张旭鹏
     * @DateTime 2023-06-25
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post();
            $params = json_decode($params['data'], true);
            $result = false;
            Db::startTrans();
            try {
                $result = $this->model->allowField(true)->save($params);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success();
            } else {
                $this->error(__('No rows were inserted'));
            }
        }
        return $this->view->fetch();
    }

    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $row->goods = $this->getGoods($row);
        if ($this->request->isPost()) {
            $params = $this->request->post();
            $params = json_decode($params['data'], true);
            $result = false;
            Db::startTrans();
            try {
                $result = $row->allowField(true)->save($params);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success();
            } else {
                $this->error(__('No rows were updated'));
            }
        }
        $this->assignconfig("row", $row);
        return $this->view->fetch();
    }

    /**
     * 获取优惠券商品列表
     * @param [type] $data
     * @Author 张旭鹏
     * @DateTime 2023-06-25
     */
    private function getGoods($data)
    {
        if ($data['use_goods_ids'] != 0) {
            return HealthGoods::where('id', 'in', $data['use_goods_ids'])->field('id, goods_name,image,is_enable')->select();
        }
        return null;
    }
}
